package com.lyl.syt.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.lyl.syt.constant.sms.AliYunSmsConstant;
import com.lyl.syt.service.MsmService;
import com.lyl.syt.vo.msm.MsmVo;
import org.springframework.stereotype.Service;

@Service("aliYunSmsService")
public class AliYunSmsServiceImpl implements MsmService {


    //发送短信验证码
    @Override
    public boolean send(String phone, String code) {
        if (StrUtil.isBlank(phone)) {
            return false;
        }

        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(AliYunSmsConstant.SECRET_ID)
                // 您的AccessKey Secret
                .setAccessKeySecret(AliYunSmsConstant.SECRET_KEY);
        config.endpoint = "dysmsapi.aliyuncs.com";

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(AliYunSmsConstant.SIGN_NAME)
                .setTemplateCode(AliYunSmsConstant.TEMPLATE_CODE)
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            Client client = new Client(config);
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            System.out.println("短信发送响应 = " + JSON.toJSONString(response.getBody()));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean send(MsmVo msmVo) {
        if (StrUtil.isNotBlank(msmVo.getPhone())){
            String code = (String) msmVo.getParam().get("code");
            return send(msmVo.getPhone(),code);
        }
        return false;
    }
}
